package com.example.dance.config;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RateLimitConfig {

    @Value("${video.speed-limit:50KB}")
    private String speedLimit;

    @Bean
    public RateLimiter videoRateLimiter() {
        // 示例：1MB/s = 1,048,576 bytes/s
        return RateLimiter.create(parseSpeedLimitToBytes(speedLimit));
    }

    private double parseSpeedLimitToBytes(String limit) {
        limit = limit.replaceAll("\\s", "").toUpperCase();
        if (limit.endsWith("KB")) {
            return Double.parseDouble(limit.replace("KB", "")) * 1024;
        } else if (limit.endsWith("MB")) {
            return Double.parseDouble(limit.replace("MB", "")) * 1024 * 1024;
        } else if (limit.endsWith("B")) {
            return Double.parseDouble(limit.replace("B", ""));
        }
        throw new IllegalArgumentException("Invalid speed limit format");
    }
}
